package com.smart.car.auth.controller;

import com.smart.car.auth.config.JwtProperties;
import com.smart.car.auth.service.AuthService;
import com.smart.car.auth.utils.CookieUtils;
import com.smart.car.common.res.bean.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT鉴权中心，接收用户登录-生成token控制
 *
 * @author: zoutao
 * @date: 2021/4/29
 */
@Api(tags = "认证模块")
@Slf4j
@RestController
@RequestMapping("")
public class AuthController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthService authService;

    /**
     * 认证方法，接收用户名和密码，校验成功后，写入cookie中
     * 参数：{"username": "13312345678","password": "123456"}
     *
     * @param username 用户名
     * @param password 密码
     */
    @ApiOperation(value = "用户登录认证")
    @PostMapping(value = "/accredit")
    public ResponseResult accredit(
            @ApiParam(required = true, name = "username", value = "手机号或用户名", example = "13312345678")
            @RequestParam("username") String username,
            @ApiParam(required = true, name = "password", value = "当前用户的密码", example = "123456")
            @RequestParam("password") String password,
            HttpServletRequest request, HttpServletResponse response) {

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ResponseResult.fail(402, "用户名或密码不能为空！");
        } else {
            try {
                //验证账户，通过则生成token
                String token = authService.accredit(username, password);
                if (StringUtils.isNotBlank(token)) {
                    //将token写入cookie，分钟
                    CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getExpire());
                    return ResponseResult.ok(token, "认证通过，登陆成功！");
                } else {
                    return ResponseResult.fail(401, "登录失败，用户名或密码错误！");
                }
            } catch (Exception e) {
                log.error("生成token失败! ", e);
                e.printStackTrace();
                return ResponseResult.fail(500, "生成token失败，请稍后再试!");
            }
        }
    }

}
